package com.shihan.client;

import com.shihan.service.JSONSerializer;
import com.shihan.service.RpcDecoder;
import com.shihan.service.RpcEncoder;
import com.shihan.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description
 * @Author shihan
 * @Date 2020/8/9 11:02
 * @Version 1.0
 */
public class RpcConsumer {

    //1.创建一个线程池对象 -- 他要处理我们的自定义事件
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件处理器  UserClientHandler
    private static UserClientHandler userClientHandler;


    //3.编写方法，初始化客户端 （ 创建连接池  bootstrap  设置bootstrap  连接服务器 ）
    public static void initClient() throws InterruptedException {
        //1.初始化 userClientHandler
        userClientHandler = new UserClientHandler();

        //2.初始化客户端 （ 创建连接池  bootstrap  设置bootstrap  连接服务器 ）
        NioEventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                //设置通道为 NIO 类型的
                .channel(NioSocketChannel.class)
                //设置请求协议为 TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听 channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取 ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addFirst(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });

        //连接服务端
        bootstrap.connect("127.0.0.1",9990).sync();

    }


    //4.编写一个方法，使用JDK动态代理创建对象
    // serviceClass:接口类型，根据哪个接口生成子类代理对象；
    // providerParam: "UserService#sayHello#"
    public static Object createProxy(Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.初始化客户端 client
                        if(userClientHandler == null){
                            initClient();
                        }

                        RpcRequest request = new RpcRequest();
                        String requestId = UUID.randomUUID().toString();
                        System.out.println(requestId);

                        String className = method.getDeclaringClass().getName();
                        String methodName = method.getName();

                        Class<?>[] parameterTypes = method.getParameterTypes();

                        request.setRequestId(requestId);
                        request.setClassName(className);
                        request.setMethodName(methodName);
                        request.setParameters(args);
                        request.setParameterTypes(parameterTypes);

                        userClientHandler.setParam(request);
                        System.out.println(requestId);
                        System.out.println("参数设置完成");

                        return executorService.submit(userClientHandler).get();
                    }
                });
    }

}
